package com.xy.blog.zuul.swagger2;

import org.springframework.cloud.netflix.zuul.filters.Route;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zanhonglei
 * @version V1.0
 * @Description: SwaggerResourcesProvider 是资源提供者，我们重写他，把各个微服务的资源路径返回，
 * 即：resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", “v2/api-docs”)));
 * 参看InMemorySwaggerResourcesProvider写法，如下，默认是当前应用的/v2/api-docs。
 * @date 2019/11/10 6:07 下午
 */
@Component
@Primary
public class GatewaySwaggerResourcesProvider implements SwaggerResourcesProvider {

    private final RouteLocator routeLocator;

    public GatewaySwaggerResourcesProvider(RouteLocator routeLocator) {
        this.routeLocator = routeLocator;
    }

    private static final String EXCLUDE_SERVICE_NAME = "xy-blog-eureka";


    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<Route> routes = routeLocator.getRoutes();
        for (Route route : routes) {
            if (!route.getFullPath().contains(EXCLUDE_SERVICE_NAME)) {
                resources.add(swaggerResource(route.getId(), route.getFullPath().replace("**", "v2/api-docs")));
            }
        }
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("2.0");
        return swaggerResource;
    }
}